package com.example.imgmarker;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.imgmarker.R;
import com.example.imgmarker.bean.PointBean;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

public class ImageLayout extends FrameLayout implements  View.OnTouchListener {

    private static final String TAG = "ImageLayout";
    private ArrayList<PointBean> points;
    private FrameLayout layouPoints;
    private ImageView imgBg;
    private OnClickViewPositionListener onClickViewPositionListener;
    private OnClickMarkerListener onClickMarkerListener;
    private OnChangePositionListener onChangePositionListener;

    private int pointWidth; //图标宽
    private int pointHeight;//图标高
    private int pointWidthOffset;//偏移量
    private int pointHeightOffset;

    private float startPositionW;//判断移动/点击
    private float startPositionH;

    private Context mContext;
    private View imgPointLayout;
    private int layoutHeight;
    private int layoutWidth;
    private long imgTimeDown;
    private boolean isLongClick;
    private float imgDownX;
    private float imgDownY;
    private long imgTimeMove;

    public ImageLayout(Context context) {
        this( context, null );
    }

    public ImageLayout(Context context, AttributeSet attrs) {
        this( context, attrs, 0 );
    }

    public ImageLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super( context, attrs, defStyleAttr );
        initView( context, attrs );
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure( widthMeasureSpec, heightMeasureSpec );
    }


    /**
     * 点击layout（空白区）
     * wPercent:宽度百分比
     * hPercent:高度百分比
     */
    public interface OnClickViewPositionListener {
        void onClickPercent(double wPercent, double hPercent);
    }


    /**
     * 改变位置(改变标记点位置)
     * wPercent:宽度百分比
     * hPercent:高度百分比
     */
    public interface OnChangePositionListener {
        void onChangePercent(int position, double wPercent, double hPercent);
    }

    /**
     * 点击标记
     */
    public interface OnClickMarkerListener {
        void onClickPosition(int position);
    }

    public void setOnClickViewPositionListener(OnClickViewPositionListener onClickViewPositionListener) {
        this.onClickViewPositionListener = onClickViewPositionListener;
    }

    public void setOnClickMarkerListener(OnClickMarkerListener onClickMarkerListener) {
        this.onClickMarkerListener = onClickMarkerListener;
    }

    public void setOnChangePositionListener(OnChangePositionListener onChangePositionListener) {
        this.onChangePositionListener = onChangePositionListener;
    }

    /**
     * 初始化view
     *
     * @param context
     * @param attrs
     */
    private void initView(Context context, AttributeSet attrs) {

        mContext = context;
        pointWidth = dp2px( mContext, 20 );//图标宽
        pointHeight = dp2px( mContext, 30 );//图标高

        pointWidthOffset = pointWidth / 2;//图标x偏移量
        pointHeightOffset = (pointHeight / 3) * 2;//图标y偏移量

        imgPointLayout = inflate( context, R.layout.layout_imgview_point, this );
        imgBg = (ImageView) imgPointLayout.findViewById( R.id.imgBg );
        layouPoints = (FrameLayout) imgPointLayout.findViewById( R.id.layouPoints );
    }

    /**
     * 设置背景图
     *
     * @param width  layout宽
     * @param height layout高
     * @param imgUrl 图片地址
     */
    public void setImgBg(int width, int height, String imgUrl) {

        layoutWidth = width;
        layoutHeight = height;

        ViewGroup.LayoutParams lp = imgBg.getLayoutParams();
        lp.width = width;
        lp.height = height;

        imgBg.setLayoutParams( lp );

        ViewGroup.LayoutParams lp1 = layouPoints.getLayoutParams();
        lp1.width = width;
        lp1.height = height;

        layouPoints.setLayoutParams( lp1 );

        Log.e( TAG, "setImgBg" + width + ":wh:" + height );
        Glide.with( mContext ).load( imgUrl ).into( imgBg );
    }


    /**
     * 设置点
     *
     * @param points 点
     */
    public void setPoints(ArrayList<PointBean> points) {
        if (layoutWidth <= 0 || layoutHeight <= 0) {
            return;
        }
        if (points == null) {
            return;
        }
        this.points = points;
        layouPoints.removeAllViews();

        for (int i = 0; i < points.size(); i++) {

            double width_scale = points.get( i ).widthScale;
            double height_scale = points.get( i ).heightScale;

            ImageView imageView = (ImageView) LayoutInflater.from( mContext ).inflate( R.layout.layout_img_point, this, false );
            imageView.setTag( i );

            LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams();
            //根据需求自行调整icon位置
            int w = (int) ((layoutWidth * width_scale) - pointWidthOffset);//x的中间
            int h = (int) ((layoutHeight * height_scale) - pointHeightOffset);//图标y的底部
            layoutParams.leftMargin = w;
            layoutParams.topMargin = h;

            imageView.setOnTouchListener( this );

            layouPoints.addView( imageView, layoutParams );
        }
    }

    /**
     * 触摸监听（获取点击手势）
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            /**
             * 屏幕开始的位置
             */
            case MotionEvent.ACTION_DOWN:
                startPositionW = event.getX();
                startPositionH = event.getY();
                Log.e( TAG, "位置：(开始)x" + startPositionW + ",y" + startPositionH );
                break;

            /**
             * 离开屏幕的位置
             */
            case MotionEvent.ACTION_UP:
                if (Math.abs( startPositionW - event.getX() ) < 100 && Math.abs( startPositionH - event.getY() ) < 100) {//点击
                    Log.e( TAG, "位置：(点击)" );
                    Log.e( TAG, "位置：(结束)百分比x" + getPercent( event.getX(), getMeasuredWidth() ) + "：y：" +
                            getPercent( event.getY(), getMeasuredHeight() ) );
                    if (onClickViewPositionListener != null) {
                        onClickViewPositionListener.onClickPercent( getPercent( event.getX(), getMeasuredWidth() )
                                , getPercent( event.getY(), getMeasuredHeight() ) );
                    }
                } else {
                    //移动
                    Log.e( TAG, "位置：(移动)" );
                }
                break;

        }
        return true;
    }


    /**
     * imageView监听
     *
     * @param view
     * @param event
     * @return
     */
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d( TAG, "onTouch: ACTION_DOWN" );
                imgTimeDown = System.currentTimeMillis();
                isLongClick = false;
                imgDownX = event.getX();
                imgDownY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d( TAG, "onTouch: ACTION_MOVE" );
                imgTimeMove = System.currentTimeMillis();
                long durationMs = imgTimeMove - imgTimeDown;
                Log.d( TAG, "onTouch: durationMs=" + durationMs );
                if (Math.abs( imgDownX - event.getX() ) < 100 && Math.abs( imgDownY - event.getY() ) < 100 && durationMs > 500) {
                    isLongClick = true;
                }
                if (isLongClick) {
                    Log.d( TAG, "onTouch: isLongClick=" + isLongClick );
                    //长按事件，可以移动
                    //重新设置控件的位置。原位置加移动位置减去标记偏移量
                    float mX = view.getX() + event.getX() ;
                    float mY = view.getY() + event.getY() ;
                    //限制移动范围
                    if (mX < 0) {
                        mX = 0;
                    }
                    if (mX > getMeasuredWidth()) {
                        mX = getMeasuredWidth();
                    }
                    if (mY < 0) {
                        mY = 0;
                    }
                    if (mY > getMeasuredHeight()) {
                        mY = getMeasuredHeight();
                    }
                    view.setX( mX - pointWidthOffset);
                    view.setY( mY - pointHeightOffset);
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d( TAG, "onTouch: ACTION_UP" );
                if (isLongClick) {//长按
                    Log.d( TAG, "onTouch: ACTION_UP是长按：" +
                            "tag:" + (int) view.getTag() +
                            "最终位置x:" + view.getX() + ":y:" + view.getY() );
                    if (onChangePositionListener != null) {
                        onChangePositionListener.onChangePercent( (int) view.getTag(), getPercent( view.getX()+pointWidthOffset, getMeasuredWidth() ),
                                getPercent( view.getY()+pointHeightOffset, getMeasuredHeight() ) );
                    }
                }
                if (Math.abs( imgDownX - event.getX() ) < 100 && Math.abs( imgDownY - event.getY() ) < 100 && !isLongClick) {//点击
                    if (onClickMarkerListener != null) {
                        int index = (int) view.getTag();
                        onClickMarkerListener.onClickPosition( index );
                    }
                }
                break;
        }
        return true;
    }

    /**
     * 将dp转换为与之相等的px
     */
    public static int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    //百分比计算
    public static double getPercent(double d, double e) {
        double p = d / e;
        DecimalFormat nf = (DecimalFormat) NumberFormat.getPercentInstance();
        nf.applyPattern( "0.00" );
        nf.setMaximumFractionDigits( 5 ); //表示精确到小数点后n位
        return Double.parseDouble( nf.format( p ) );
    }

}
